package cae.gui.util;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class CaePopUpButton extends JToggleButton
{
	private static final long serialVersionUID = 1L;
	private JPopupMenu popupMenu = new JPopupMenu(); //el que representa el popup
	private boolean popupInvisible = true; //que representa si el popup es invisible o no

	public CaePopUpButton(Icon icon)
	{
		super(icon);
		
		//popupMenu.setLayout(new BoxLayout(popupMenu, BoxLayout.X_AXIS));
	     setFocusable(false);
	     putClientProperty("JButton.buttonType", "textured");
	     addMouseListener(createButtonMouseListener());
	     popupMenu.addPopupMenuListener(createPopupMenuListener());
	     JComboBox box = new JComboBox();
	     Object preventHide = box.getClientProperty("doNotCancelPopup");
	     putClientProperty("doNotCancelPopup", preventHide);
	}
	
	private MouseListener createButtonMouseListener() {
	      return new MouseAdapter() {
	     @Override
	     public void mousePressed(MouseEvent e) {
	          if (popupMenu.isShowing()) {
	        	  hidePopupMenu();
	          } else {
	              showPopupMenu();
	        }}

		};}
	
	private void showPopupMenu() {
		popupMenu.show(this, 10, 10);
	}

	private void hidePopupMenu() {
		popupMenu.setVisible(false);
		
	}
	
	public void addItem(JMenuItem item){
	     popupMenu.add(item);
	}
	
	private PopupMenuListener createPopupMenuListener() {
	     return new PopupMenuListener() {
	           public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
	            };
	           public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
	                if (popupInvisible) {
	                   setSelected(false);
	                }
	            }
	         public void popupMenuCanceled(PopupMenuEvent e) {
	               setSelected(false);
	}};}
}
